package com.yusp75.myexam.com.yusp75.myexam.util

import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.FragmentActivity


class FilePickerUtil(
    private val context: FragmentActivity,
    private val onFileSelected: (Uri) -> Unit
) {
    private val filePickerLauncher = context.registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        result.data?.data?.also { uri ->
            if (isValidXlsx(uri)) {
                onFileSelected(uri)
            } else {
                Toast.makeText(context, "无效文件类型", Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun launchPicker() {
        val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
            type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            addCategory(Intent.CATEGORY_OPENABLE)
        }
        filePickerLauncher.launch(intent)
    }

    private fun isValidXlsx(uri: Uri): Boolean {
        return context.contentResolver.getType(uri)?.contains("spreadsheetml") == true ||
                uri.path?.endsWith(".xlsx", ignoreCase = true) == true
    }
}
